package com.zjt.smart.manager;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;

import com.zjt.smart.app.MainApplication;
import com.zjt.smart.mvp.model.Event;
import com.zjt.smart.observer.EventObserver;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件总线管理类
 */
public class EventManager {
    private static EventManager INSTANCE = new EventManager();
    List<EventObserver> observers = new ArrayList<EventObserver>();
    private Handler handler;

    private EventManager() {
        handler = new Handler(MainApplication.getApp().getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                Event event = (Event) msg.obj;
                handleEvent(event);
            }
        };
    }

    public static EventManager getInstance() {
        if (MainApplication.sEventManager == null){
            MainApplication.sEventManager = new EventManager();
        }
        return MainApplication.sEventManager;
    }

    public void regist(@NonNull EventObserver observer) {
        synchronized (this) {
            if (!observers.contains(observer))
                observers.add(observer);
        }
    }

    public int count() {
        return observers.size();
    }

    public synchronized void unregist(EventObserver observer) {
        observers.remove(observer);
    }

    public synchronized void clear() {
        observers.clear();
    }

    public void postMessage(int what){
        postEvent(new Event(what));
    }

    @SuppressWarnings("unchecked")
    public void postEvent(Event event) {
        Message message = Message.obtain();
        message.obj = event;
        handler.sendMessage(message);
    }

    private void handleEvent(Event event){
        if (event == null) return;
        int size = 0;
        EventObserver[] arrays;
        synchronized (this) {
            size = observers.size();
            arrays = new EventObserver[size];
            observers.toArray(arrays);

        }
        if (arrays != null) {
            for (EventObserver observer : arrays) {
                observer.onEvent(event);
            }
        }
    }

}
